/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.cspimp.em.service.impl;

import me.zhengjie.exception.EntityExistException;
import me.zhengjie.modules.cspimp.em.domain.Material;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.cspimp.em.repository.MaterialRepository;
import me.zhengjie.modules.cspimp.em.service.MaterialService;
import me.zhengjie.modules.cspimp.em.service.dto.MaterialDto;
import me.zhengjie.modules.cspimp.em.service.dto.MaterialQueryCriteria;
import me.zhengjie.modules.cspimp.em.service.mapstruct.MaterialMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
 * @author zmm
 * @website https://docs.auauz.net
 * @description 服务实现
 * @date 2020-05-24
 **/
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class MaterialServiceImpl implements MaterialService {

    private final MaterialRepository materialRepository;
    private final MaterialMapper materialMapper;

    @Override
    public Map<String, Object> queryAll(MaterialQueryCriteria criteria, Pageable pageable) {
        Page<Material> page = materialRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(materialMapper::toDto));
    }

    @Override
    public List<MaterialDto> queryAll(MaterialQueryCriteria criteria) {
        return materialMapper.toDto(materialRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public MaterialDto findById(Long id) {
        Material material = materialRepository.findById(id).orElseGet(Material::new);
        ValidationUtil.isNull(material.getId(), "Material", "id", id);
        return materialMapper.toDto(material);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MaterialDto create(Material resources) {
        if (materialRepository.findByName(resources.getName()) != null) {
            throw new EntityExistException(Material.class, "name", resources.getName());
        }
        resources.setCid(0l);
        return materialMapper.toDto(materialRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Material resources) {
        Material material = materialRepository.findById(resources.getId()).get();
        ValidationUtil.isNull( material.getId(),"Material","id",resources.getId());

        Material m = materialRepository.findByName(resources.getName());

        if(m != null && !m.getId().equals(material.getId())){
            throw new EntityExistException(Material.class,"name",resources.getName());
        }

        material.copy(resources);
        materialRepository.save(material);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            materialRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<MaterialDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (MaterialDto material : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put(" cid", material.getCid());
            map.put("物资名称", material.getName());
            map.put("物资数量", material.getMaterialCount());
            map.put("物资单位", material.getUnit());
            map.put("物资周期", material.getCycle());
            map.put("创建时间", material.getCreateTime());
            map.put("更新时间", material.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}